<template>
  <div v-loading="loading">
    <el-row class="gl_my_15">
      <el-col :span="3">
        <el-button size="mini" type="primary" @click="addAddress">新增收货地址</el-button>
      </el-col>
      <el-col :span="21" class="gl_fs_12" style="color:#bdbdbd;line-height:28px;">您已创建{{ tableData.length }}个收货地址，最多可创建15个</el-col>
    </el-row>
    <el-row>
      <div v-if="total > 0">
        <el-card v-for="item in tableData" :key="item.id" class="cardAdd" shadow="hover">
          <el-row class="gl_mb_10 gl_fs_16 gl_ft_weight title_name">{{ item.consigneeName }}<span v-if="item.isDefault" class="defaultAdd" style="display:inline-block;">默认地址</span></el-row>
          <el-row>
            <el-col :span="3" style="text-align:right;">收货人：</el-col>
            <el-col :span="21" class="gl_pl_10">{{ item.consigneeName }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="3" style="text-align:right;">所在地址：</el-col>
            <el-col :span="21" class="gl_pl_10">{{ addressDataForCheck(item.provinceCode, item.cityCode, item.countyCode) }} {{ item.address }}</el-col>
          </el-row>
          <el-row>
            <el-col :span="3" style="text-align:right;">手机：</el-col>
            <el-col :span="7" class="gl_pl_10">{{ item.phoneNumber }}</el-col>
            <el-col :span="14" style="text-align:right;">
              <el-button v-if="!item.isDefault" size="mini" type="text" @click="clickDefault(item.id)">设为默认</el-button>
              <el-button size="mini" type="text" @click="clickEdit(item)">编辑</el-button>
              <el-button v-if="!item.isDefault" size="mini" type="text" style="color:#FF3434" @click="clickDelete(item.id)">删除</el-button>
            </el-col>
          </el-row>
        </el-card>
      </div>
      <div v-else class="gl_noData">
        <p>暂无数据</p>
      </div>
    </el-row>
    <el-dialog
      :title="title"
      class="gl_dialog_TitleLine gl_dl_footer"
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :before-close="clickCancel"
      width="640px"
    >
      <el-scrollbar ref="scroll" v-loading="dialogLoading" wrap-class="scrollbar-wrapper">
        <el-form ref="selectedMsg" class="gl_form_mini gl_px_30" :model="selectedMsg" :rules="selectedMsg_Rules" label-position="right" label-width="120px" style="padding:0px 30px;">
          <el-form-item label="收货人姓名" prop="consigneeName">
            <el-input v-model="selectedMsg.consigneeName" maxlength="10" placeholder="请输入" type="text" size="mini" />
          </el-form-item>
          <el-form-item label="配送区域" prop="provinceCode">
            <el-cascader v-model="selectedMsg.area" size="mini" :options="cache.district" :props="{ value: 'code', label: 'name' }" placeholder="请选择省市区" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="selectedMsg.address" placeholder="请输入" maxlength="200" type="textarea" :rows="4" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话" prop="phoneNumber">
            <el-input v-model="selectedMsg.phoneNumber" placeholder="请输入" maxlength="11" type="text" size="mini" />
          </el-form-item>
        </el-form>
      </el-scrollbar>
      <span slot="footer" class="dialog-footer">
        <!-- 取消按钮 -->
        <el-button size="mini" @click="clickCancel">{{ $t('button.cancel') }}</el-button>
        <!-- 编辑的保存按钮 -->
        <el-button v-if="type === 'edit'" type="primary" size="mini" @click="confirmEdit()">确 定</el-button>
        <!-- 新增的保存按钮 -->
        <el-button v-else type="primary" size="mini" @click="confirmAdd()">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex';
import { deepCopy } from '@/lib';
import {
  api_GET_MallDeliveryAddress,
  api_POST_MallDeliveryAddress,
  api_PUT_MallDeliveryAddressId,
  api_DELETE_MallDeliveryAddressId,
  api_POST_MallDeliveryAddressIdSetDefault
} from '@/extend/api/shoppingmallswaggerApi/app.js';
import {
  Api_GET_MallDeliveryAddressQO,
  SiSTKWMallDeliveryAddressCreateInput // 创建更新
} from '@/lib/form/shoppingmall/swaggerForm.js';
import validator from '@/lib/validate/index.js';
export default {
  data() {
    return {
      loading: false,
      dialogLoading: false,
      total: 0,
      tableData: [],
      dialogVisible: false,
      selectedMsg: new SiSTKWMallDeliveryAddressCreateInput(),
      getMsg: new Api_GET_MallDeliveryAddressQO(),
      selectedMsg_Rules: {
        consigneeName: [
          { required: true, message: '收货人不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              callback(validator.checkConsigneeName(value, '收货人姓名不能超过10个字'));
            },
            trigger: 'blur'
          }],
        phoneNumber: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          {
            validator(rule, value, callback) {
              callback(validator.checkPhone(value, '手机号格式错误'));
            },
            trigger: 'blur'
          }],
        address: [{ required: true, message: '详细地址不能为空', trigger: 'blur' }],
        provinceCode: [{ required: true, message: '所在地区不能为空', trigger: 'blur' }]
      },
      type: 'edit',
      area: [],
      registerId: ''
    };
  },
  computed: {
    ...mapState({
      UserType: state => state.user.currentUserType,
      dict: state => state.dict.dict,
      cache: state => state.dict.cache
    }),
    title: function() {
      return this.type === 'edit' ? '编辑收货地址' : '新增收货地址';
    }
  },
  watch: {
    'UserType': {
      immediate: true,
      deep: true,
      handler(val) {
        if (val && val.registerId) {
          this.registerId = val.registerId;
          this.selectedMsg.registerId = val.registerId;
          this.getMsg.RegisterId = val.registerId;
        }
      }
    }
  },
  created() {
    this.getDictByType(['district']);
    this.getDict();
    this.getList();
  },
  methods: {
    // 若没有字典信息，外部可直接调用方法获取字典数据
    ...mapActions({ getDict: 'dict/getDict', getDictByType: 'dict/getDictByType' }),
    getList() {
      const that = this;
      this.loading = true;
      this.getMsg.MaxResultCount = 15;
      api_GET_MallDeliveryAddress(this.getMsg).then(res => {
        this.loading = false;
        this.total = res.length;
        this.tableData = res;
        this.tableData = this.tableData.map(item => {
          that.$set(item, 'area', [item.provinceCode, item.cityCode, item.countyCode]);
          return item;
        });
      }, error => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        this.$message({ type: 'error', message: _msg });
      });
    },
    // 新增收货地址
    addAddress() {
      if (this.total >= 15) {
        this.$message({ type: 'warning', message: '您已创建15个收货地址，最多可创建15个' });
        return;
      }
      this.dialogVisible = true;
      this.type = 'add';
    },
    // 设为默认
    clickDefault(id) {
      const that = this;
      this.loading = true;
      api_POST_MallDeliveryAddressIdSetDefault(id).then(res => {
        this.loading = false;
        this.getList();
      }, error => {
        this.loading = false;
        const _msg = error.error.message || error.message;
        that.$message({ type: 'error', message: _msg });
      });
    },
    // 处理省市区
    addressDataForCheck (_provinceCode, _cityCode, _countyCode) {
      let _provinceData;
      let _cityData;
      let _countyData;
      if (_provinceCode && this.cache.district) {
        _provinceData = this.cache.district.find(item => item.code === _provinceCode);
      }
      if (_cityCode && _provinceData) {
        _cityData = _provinceData.children.find(item => item.code === _cityCode);
      }
      if (_countyCode && _cityData) {
        _countyData = _cityData.children.find(item => item.code === _countyCode);
      }
      _provinceData = _provinceData ? _provinceData.name : '';
      _cityData = _cityData ? _cityData.name : '';
      _countyData = _countyData ? _countyData.name : '';
      return `${_provinceData} ${_cityData} ${_countyData}`;
    },
    clickEdit(item) {
      item.area[0] = item.provinceCode;
      item.area[1] = item.cityCode;
      item.area[2] = item.countyCode;
      this.dialogVisible = true;
      this.type = 'edit';
      this.addressId = item.id;
      this.selectedMsg = deepCopy(item);
    },
    clickDelete(id) {
      const that = this;
      this.$confirm(`您确定要删除此地址吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          api_DELETE_MallDeliveryAddressId(id).then(res => {
            that.$message({ type: 'success', message: '删除成功' });
            that.getList();
          }, error => {
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        })
        .catch(() => {
        });
    },
    // 新增地址
    confirmAdd() {
      this.type = 'add';
      const that = this;
      that.selectedMsg.provinceCode = that.selectedMsg.area ? that.selectedMsg.area[0] : that.selectedMsg.provinceCode;
      that.selectedMsg.cityCode = that.selectedMsg.area ? that.selectedMsg.area[1] : that.selectedMsg.cityCode;
      that.selectedMsg.countyCode = that.selectedMsg.area ? that.selectedMsg.area[2] : that.selectedMsg.countyCode;
      // that.selectedMsg.registerId = that.registerId;
      this.$refs.selectedMsg.validate(valid => {
        if (valid) {
          // if (!that.selectedMsg.registerId) return;
          that.dialogLoading = true;
          api_POST_MallDeliveryAddress(that.selectedMsg).then(res => {
            that.dialogLoading = false;
            that.dialogVisible = false;
            that.$message({ type: 'success', message: '添加成功' });
            this.getList();
            that.selectedMsg = new SiSTKWMallDeliveryAddressCreateInput();
            that.selectedMsg.area = [];
          }, error => {
            that.dialogLoading = false;
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        } else {
          that.$refs.scroll.wrap.scrollTop = 0;
          that.dialogVisible = true;
          return false;
        }
      });
    },
    // 编辑地址
    confirmEdit() {
      const that = this;
      this.$refs.selectedMsg.validate(valid => {
        if (valid) {
          if (!that.addressId) return;
          that.selectedMsg.provinceCode = that.selectedMsg.area[0];
          that.selectedMsg.cityCode = that.selectedMsg.area[1];
          that.selectedMsg.countyCode = that.selectedMsg.area[2];
          that.dialogLoading = true;
          api_PUT_MallDeliveryAddressId(that.addressId, that.selectedMsg).then(res => {
            that.dialogLoading = false;
            that.dialogVisible = false;
            that.$message({ type: 'success', message: '修改成功' });
            that.getList();
            that.selectedMsg = new SiSTKWMallDeliveryAddressCreateInput();
            that.selectedMsg.area = [];
          }, error => {
            that.dialogLoading = false;
            const _msg = error.error.message || error.message;
            that.$message({ type: 'error', message: _msg });
          });
        } else {
          that.dialogLoading = false;
          that.$refs.scroll.wrap.scrollTop = 0;
          that.dialogVisible = true;
          return false;
        }
      });
    },
    clickCancel() {
      this.dialogVisible = false;
      this.selectedMsg = new SiSTKWMallDeliveryAddressCreateInput();
      this.selectedMsg.area = [];
    }
  }
};
</script>

<style scoped>
.defaultAdd {
  display: inline-block;
  width: 70px;
  height: 20px;
  background: rgba(226, 52, 53, 1);
  text-align: center;
  font-size: 12px;
  line-height: 20px;
  color: white;
  margin-left: 10px;
}
.title_name {
  height: 30px;
  line-height: 30px;
  padding-left: 20px;
}
.cardAdd {
  line-height: 35px;
  font-size: 14px;
  width: 80%;
  margin-bottom: 15px;
}
</style>
